import React, { Component } from 'react'
import { connect } from 'dva';

import { Button, Form, Select } from 'antd';

const FormItem = Form.Item;
const Option = Select.Option;

export interface IProps {
  dispatch?: Function,
  children?: React.ReactNode,
  history: any,
  form: any,
  groups: Array<any>,
  details: {
    loginName: string,
    groupList: Array<IRole>,
    id: number
  }
  match: {
    params: {
      id: string
    }
  }
}

interface IRole {
  id: number | string,
  name: string
}

@connect(({ person }) => ({
  details: person.details,
  groups: person.groups
}))
class AuthorizationForm extends Component<IProps> {

  componentDidMount() {
    const { dispatch, match } = this.props;
    const { params } = match;

    dispatch({
      type: 'person/queryGroupTree',
      payload: {
        id: params.id,
        callback: (details) => {
          const { form } = this.props;
          if (details && details.groupList) {
            const groups = details.groupList.map(item => item.id);
            form.setFieldsValue({ groups })
          }
        }
      },
    })
  }

  handleSubmit = (e) => {
    e.preventDefault();

    const { form, dispatch, details } = this.props;
    form.validateFields((err, values) => {
      if (!err) {
        dispatch({
          type: 'person/allotGroups',
          payload: {
            userId: details.id,
            groupIdList: values.groups
          }
        })
      }
    })
  }

  render() {
    const { form, details, groups = [] } = this.props;
    const { getFieldDecorator } = form;
    const formItemLayout = {
      labelCol: { span: 3 },
      wrapperCol: { span: 10 },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 16, offset: 2 },
      },
    };

    return (
      <>
        <Form onSubmit={this.handleSubmit}>
          <FormItem label="人员" {...formItemLayout}>{ details.loginName }</FormItem>
          <FormItem label="部门列表" {...formItemLayout} >
            {getFieldDecorator('groups', {
              rules: [{ type: 'array' }],
            })(
              <Select mode="multiple" placeholder="请选择用户列表">
                {
                  groups.map(item => (
                    <Option value={item.id} key={item.id}>{ item.name }</Option>
                  ))
                }
              </Select>
            )}
          </FormItem>
          <FormItem {...tailFormItemLayout}>
            <Button type="primary" htmlType="submit" style={{marginRight: '20px'}}>提交</Button>
            <Button onClick={() => window.history.back()}>返回</Button>
          </FormItem>
        </Form>
      </>
    )
  }
}

const Authorization = Form.create()(AuthorizationForm);
export default Authorization;
